package com.teng.mylibrary.widget

import android.view.View
import com.teng.mylibrary.Constants
import com.teng.mylibrary.base.BaseDialog
import com.teng.mylibrary.databinding.DialogIpAddBinding
import com.teng.mylibrary.entity.EventMsg
import com.teng.mylibrary.util.ToastHelper
import org.greenrobot.eventbus.EventBus
import java.util.regex.Matcher
import java.util.regex.Pattern

/**
 * Description:
 * Author:         liuteng
 * CreateDate:     2022年9月23日
 * UpdateRemark:   更新说明
 */
class IPAddDialog : BaseDialog<DialogIpAddBinding>(DialogIpAddBinding::inflate) {

    var mOnItemOkListener: ((content: String) -> Any?)? = null

    override fun initView(view: View?) {
        binding.btnOk.setOnClickListener {
            if (binding.etIp.text.isEmpty()) {
                ToastHelper.showOther(context, "请输入IP地址")
                return@setOnClickListener
            }
            if (!isCorrectIp(binding.etIp.text.toString())) {
                ToastHelper.showOther(context, "IP地址不正确")
                return@setOnClickListener
            }
            val ipAddress = StringBuilder("http://")
            ipAddress.append(binding.etIp.text.trim())
            if (binding.etPort.text.isNotEmpty()) {
                ipAddress.append(":")
                ipAddress.append(binding.etPort.text)
            }
            ipAddress.append("/")
            mOnItemOkListener?.invoke(ipAddress.toString())
            dismiss()
        }
        binding.btnCancel.setOnClickListener { dismiss() }
    }

    override fun initData() {
    }

    /** * 判断是否为合法IP  */
    private fun isCorrectIp(ipAddress: String): Boolean {
        val ip =
            "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}"
        val pattern: Pattern = Pattern.compile(ip)
        val matcher: Matcher = pattern.matcher(ipAddress)
        return matcher.matches()
    }

    /**
     * 确认
     */
    fun setOnItemOkListener(onItemOkListener: ((content: String) -> Any?)) {
        mOnItemOkListener = onItemOkListener
    }
}